package timer;

import java.util.PriorityQueue;

/**
 * @Author liangzai
 * @Description:
 */

class MyTask implements Comparable<MyTask>{
    private long time;
    private Runnable runnable;

    public MyTask(long time, Runnable runnable) {
        this.time = time;
        this.runnable = runnable;
    }

    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

public class MyTimer {
    private Object locker = new Object();
    private PriorityQueue<MyTask> queue;

    public MyTimer (){
        queue = new PriorityQueue<>(1000);
        Thread thread = new Thread(()->{
            synchronized (locker){
                try{
                    while(true){
                        if(queue.isEmpty()){
                            locker.wait();
                        }
                        long time = queue.peek().getTime();
                        if(time>System.currentTimeMillis()){
                            locker.wait(time-System.currentTimeMillis());
                            continue;
                        }
                        queue.poll().getRunnable().run();
                    }
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable ,long time){
        synchronized(locker){
            MyTask task = new MyTask(time+System.currentTimeMillis(), runnable);
            queue.offer(task);
            locker.notify();
        }
    }
}

class Main{
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        Thread thread = new Thread(()->{
            timer.schedule(()->{
                System.out.println("hello 3000!");
            },3000);
            timer.schedule(()->{
                System.out.println("hello 2000!");
            },2000);
            timer.schedule(()->{
                System.out.println("hello 1000!");
            },1000);
        });
        thread.start();
        thread.join();
    }
}
